var express = require('express')
var router = express.Router()

const { getALL, getById, exec } = require('../db')

// 获取所有留言
// GET/messages
router.get('/', async (req, res) => {
  //解析请求参数
  const { page = 1, size = 5 } = req.query
  //定义偏移量
  let offset = (page - 1) * size
  let count = `select count(*) as total from messages`
  let { total } = await getById(count)
  //操作数据库
  let sql = `select * from messages order by id desc limit ${offset}, ${size} `
  //返回结果
  console.log(sql)

  const data = await getALL(sql)
  res.send({
    code: 0,
    message: '获取留言成功',
    result: {
      total,
      data,
    },
  })
})

//获取单个留言
// GET/messages/:id
router.get('/:id', async (req, res) => {
  //解析请求参数
  const { id } = req.params
  //操作数据库
  let sql = `select * from messages where id = ${id}`
  //返回结果
  console.log(sql)

  const data = await getById(sql)
  res.send({
    code: 0,
    message: '获取留言成功',
    result: {
      data,
    },
  })
})

// 新增留言
// POST
router.post('/', async (req, res) => {
  // 解析请求参数
  const { name, content, url } = req.body
  // 操作数据库
  let sql = `insert into messages(name,content,url) values('${name}','${content}','${url}')`
  // 返回结果
  const data = await exec(sql)
  res.send({
    code: 0,
    message: '添加留言成功',
    result: {
      data,
      name,
      content,
      url,
    },
  })
})

//删除留言
router.delete('/:id', async (req, res) => {
  //解析请求参数
  const { id } = req.params
  //操作数据库
  let sql = `delete from messages where id = '${id}'`
  //返回结果
  const data = await exec(sql)
  res.send({
    code: 0,
    message: '删除留言成功',
    result: {
      data,
    },
  })
})
//导出
module.exports = router
